#include <optional>
#include <nice2d/sprite.h>
#include <nice2d/colorgradient.h>
#include <nice2d/actions/colorizedaction.h>

class ColorizedActionData
{
public:
    sf::Color srcColor;
    sf::Color dstColor;
    std::optional<float> elaspedTime;
};

ColorizedAction::ColorizedAction(const sf::Color& dstColor,float duration):
    FiniteTimeAction(duration),
    data(new ColorizedActionData())
{
    data->dstColor = dstColor;
}

ColorizedAction::~ColorizedAction()
{
}

void ColorizedAction::update(float deltaTime)
{
    auto owner = getOwner();
    if (owner.expired())
        return;

    auto target = std::dynamic_pointer_cast<Sprite>(owner.lock());
    assert(target && "ColorizedAction's owner must be sprite!");

    if (!data->elaspedTime.has_value()) {
        data->elaspedTime = 0.0f;
        data->srcColor = target->getSpriteColor();
    }

    if (data->elaspedTime.has_value()) {
        float time = data->elaspedTime.value();
        time += deltaTime;
        float percent = time/getDuration();
        data->elaspedTime = time;
        percent = std::min(1.0f,percent);
        auto color = blendColors(data->srcColor,data->dstColor,percent);
        target->setSpriteColor(color);
        if(percent >= 1.0f) {
            stop();
        }
    }
}

sf::Color ColorizedAction::getDstColor() const
{
    return data->dstColor;
}